/* SPDX-License-Identifier: MIT */

package com.lark.view.theme;

import atlantafx.base.theme.*;
import com.lark.context.ApplicationContext;
import com.lark.layout.ModalDialog;
import com.lark.utils.AnimationUtil;
import com.lark.utils.ResourcesUtil;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

import static com.lark.context.ApplicationContext.scene;


/**
 * 主题对话框
 */
public final class ThemeDialog extends ModalDialog {

    private static final String STYLE_SHEET = ResourcesUtil.convertFilePath("static/css/thumbnail.css");
    private final TilePane thumbnailsPane = new TilePane(20, 20);
    private final ToggleGroup thumbnailsGroup = new ToggleGroup();

    public ThemeDialog() {
        super();
        header.setTitle("选择主题");
        content.setBody(createContent());
        // 更新缩略图
        updateThumbnails();

        thumbnailsGroup.selectedToggleProperty().addListener((obs, old, val) -> {
            if (val != null && val.getUserData() instanceof Theme theme) {
                ApplicationContext.theme = theme.getUserAgentStylesheet();
                AnimationUtil.animateThemeChange(Duration.millis(500), scene, ApplicationContext.theme);
                ApplicationContext.settingModel.setTheme(ApplicationContext.theme);
            }
        });
    }

    private VBox createContent() {
        thumbnailsPane.setAlignment(Pos.TOP_CENTER);
        thumbnailsPane.setPrefColumns(3);
        thumbnailsPane.setStyle("-color-thumbnail-border:-color-border-subtle;");
        thumbnailsPane.getStylesheets().add(STYLE_SHEET);
        var root = new VBox(thumbnailsPane);
        root.setPadding(new Insets(20));
        return root;
    }

    /**
     * 更新主题列表 - 缩略图
     */
    private void updateThumbnails() {
        List<Theme> themeList = Arrays.asList(new PrimerLight(), new PrimerDark(), new NordLight(), new NordDark(), new CupertinoLight(), new CupertinoDark(), new Dracula());
        thumbnailsPane.getChildren().clear();
        themeList.forEach(theme -> {
            var thumbnail = new ThemeThumbnail(theme);
            thumbnail.setToggleGroup(thumbnailsGroup);
            thumbnail.setUserData(theme);
            thumbnail.setSelected(StringUtils.equals(
                    ApplicationContext.theme,
                    theme.getUserAgentStylesheet()
            ));
            thumbnailsPane.getChildren().add(thumbnail);
        });
    }
}
